package com.lqm.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lqm.common.constant.ProductConstant;
import com.lqm.common.utils.PageUtils;
import com.lqm.common.utils.Query;
import com.lqm.mall.product.dao.AttrAttrgroupRelationDao;
import com.lqm.mall.product.dao.AttrDao;
import com.lqm.mall.product.dao.AttrGroupDao;
import com.lqm.mall.product.dao.CategoryDao;
import com.lqm.mall.product.entity.AttrAttrgroupRelationEntity;
import com.lqm.mall.product.entity.AttrEntity;
import com.lqm.mall.product.entity.AttrGroupEntity;
import com.lqm.mall.product.entity.CategoryEntity;
import com.lqm.mall.product.service.AttrService;
import com.lqm.mall.product.service.CategoryService;
import com.lqm.mall.product.vo.AttrRespVo;
import com.lqm.mall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }


    @Transactional //插入保存sql语句要开启事务
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity=new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        //保存基本数据
        this.save(attrEntity);
        //保存关联关系
        //销售属性无分组
        if(attr.getAttrType()!= ProductConstant.AttrNum.ATTR_TYPE_SALE.getCode() && attr.getAttrGroupId()!=null){
            AttrAttrgroupRelationEntity relationEntity=new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(relationEntity);
        }

    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper=new QueryWrapper<>();
        String key= (String) params.get("key");
        queryWrapper.eq("attr_type","base".equalsIgnoreCase(type)?ProductConstant.AttrNum.ATTR_TYPR_BASE.getCode():ProductConstant.AttrNum.ATTR_TYPE_SALE.getCode());
        if(catelogId!=null && catelogId!=0){
            queryWrapper.eq("catelog_id",catelogId);
        }
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper)->{
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils=new PageUtils(page);
        //增加两个冗余字段attrName,groupName
        List<AttrRespVo> respVos = page.getRecords().stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            CategoryEntity categoryEntity = categoryDao.selectById(attrRespVo.getCatelogId());
            if(categoryEntity!=null){
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            if("base".equalsIgnoreCase(type)){
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrRespVo.getAttrId()));
                if (relationEntity != null) {
                    Long attrGroupId = relationEntity.getAttrGroupId();
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                    if(attrGroupEntity!=null){
                        String attrGroupName = attrGroupEntity.getAttrGroupName();
                        attrRespVo.setGroupName(attrGroupName);
                    }
                }
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        //重置数据集
        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Cacheable(value = "attr",key = "'attrinfo:'+#root.args[0]")
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId())
        );
        if(relationEntity!=null){
            Long groupId=relationEntity.getAttrGroupId();
            attrRespVo.setAttrGroupId(groupId);
            if(groupId!=null){
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(groupId);
                if(attrGroupEntity!=null){
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        Long catelogId = attrRespVo.getCatelogId();
        Long[] catelogPath=categoryService.findCategoryPath(catelogId);
        attrRespVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if(categoryEntity!=null){
            attrRespVo.setCatelogName(categoryEntity.getName());
        }

        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity=new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);
        if(attr.getAttrType()==ProductConstant.AttrNum.ATTR_TYPE_SALE.getCode()){
            return;
        }
        AttrAttrgroupRelationEntity relationEntity=new AttrAttrgroupRelationEntity();
        relationEntity.setAttrId(attr.getAttrId());
        relationEntity.setAttrGroupId(attr.getAttrGroupId());
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper=new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",relationEntity.getAttrId());
        Integer count = relationDao.selectCount(queryWrapper);
        if(count==null || count==0){
            relationDao.insert(relationEntity);
        }else{
            relationDao.update(relationEntity,queryWrapper);
        }


    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> list=relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id",attrgroupId));
        List<Long> attrIds = list.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        if(attrIds==null || attrIds.size()==0){
            return null;
        }
        List<AttrEntity> attrEntities=this.baseMapper.selectList(
                new QueryWrapper<AttrEntity>().in("attr_id",attrIds));
        return attrEntities;
    }

    @Override
    public PageUtils getRelationNoAttr(Long attrgroupId, Map<String, Object> params) {
        //查询对应属性分组
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        //查询分类id
        Long catelogId = attrGroupEntity.getCatelogId();
        //查询分类下的其他分组id
        List<AttrGroupEntity> attrGroups=attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id",catelogId)).stream().collect(Collectors.toList());
        //查询对应属性分组下的属性id
        QueryWrapper<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityQueryWrapper = new QueryWrapper<AttrAttrgroupRelationEntity>();
        if(attrGroups!=null && !attrGroups.isEmpty()){
            attrAttrgroupRelationEntityQueryWrapper.in("attr_group_id", attrGroups.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList()));
        }
        List<AttrAttrgroupRelationEntity> attrList=relationDao.selectList(attrAttrgroupRelationEntityQueryWrapper).stream().collect(Collectors.toList());
        //查询不在其他属性分组下的属性id
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", ProductConstant.AttrNum.ATTR_TYPR_BASE.getCode());
        if(attrList!=null && !attrList.isEmpty()){
            queryWrapper.notIn("attr_id", attrList.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList()));
        }
        String key= (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper -> {
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            }));
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        List<Long> searchIds=this.baseMapper.selectSearchAttrIds(attrIds);
        return searchIds;
    }


}